package com.cloud.school.bus.teacherhelper.modules.uploadlist.uploadutils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.http.Header;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.IErrorListener;
import com.android.support.jhf.network.IStateListener;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.NetworkClientSingle;
import com.android.support.jhf.network.loopj.android.http.AsyncHttpRequest;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.TeacherHelperApplication;
import com.cloud.school.bus.teacherhelper.base.database.UploadFileDB;
import com.cloud.school.bus.teacherhelper.entitys.UploadFile;
import com.cloud.school.bus.teacherhelper.modules.uploadlist.UploadListFragment;
import com.cloud.school.bus.teacherhelper.protocol.statistics.UploadFileRequest;
import com.cloud.school.bus.teacherhelper.protocol.statistics.UploadFileResponse;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

/**
 * 文件上传类
 * 
 * @author jiahongfei
 * 
 */
public class UploadFileUtils {

	private Context mContext;
	private Fragment mFragment;
	private TeacherHelperApplication mApplication;

	private List<UploadFile> mUploadFileList = new ArrayList<UploadFile>();

	private static UploadFileUtils sUploadUtils = new UploadFileUtils();

	public static UploadFileUtils getUploadUtils() {
		return sUploadUtils;
	}

	/**
	 * 最先调用否则都不能使用,再每个界面开始的时候都需要调用
	 * 
	 * @param context
	 */
	public void setContext(Context context) {
		mContext = context;
		mApplication = (TeacherHelperApplication) mContext
				.getApplicationContext();
	}

	public void setFragment(Fragment fragment) {
		mFragment = fragment;
	}

	/**
	 * 将上传文件保存到数据库中
	 * 
	 * @param uploadFileList
	 */
	public void setUploadFileDB(List<UploadFile> uploadFileList) {
		if (null == mContext) {
			throw new NullPointerException(
					"no call method setContext(Context context)");
		}

		// 保存数据
		UploadFileDB uploadFileDB = UploadFileDB.getUploadFileDB(mContext);
		for (int j = 0; j < uploadFileList.size(); j++) {
			uploadFileDB.putInsert(uploadFileList.get(j));
		}
		uploadFileDB.close();

		mUploadFileList.addAll(uploadFileList);

	}

	/**
	 * 在数据库中读取数据，主要用在软件关闭打开得时候加载数据，继续上传
	 */
	public void readUploadFileDB() {

		if (null == mContext) {
			throw new NullPointerException(
					"no call method setContext(Context context)");
		}

		// 读取数据
		UploadFileDB uploadFileDB = UploadFileDB.getUploadFileDB(mContext);
		List<UploadFile> uploadFileList = uploadFileDB.getUploadFileList();
		uploadFileDB.close();

		mUploadFileList.clear();
		mUploadFileList.addAll(uploadFileList);
	}

	/**
	 * 开启线程上传文件，每次只上传一个其余等待,在setUploadFileDB方法之后调用
	 */
	public void uploadFileService() {
		if (null == mContext) {
			throw new NullPointerException(
					"no call method setContext(Context context)");
		}
		
		uploadFirstFile();
	}

	private void uploadFirstFile() {
		if (mUploadFileList.size() > 0) {
			UploadFile uploadFile = mUploadFileList.get(0);
			if (null == uploadFile.requestHandle) {
				uploadFile(mUploadFileList.get(0));
			}
		}
	}

	public List<UploadFile> getUploadFiles() {
		return mUploadFileList;
	}

	public void remove(UploadFile uploadFile) {
		int removeIndex = 0;
		for (int i = 0; i < mUploadFileList.size(); i++) {
			if (mUploadFileList.get(i).picPathString
					.equals(uploadFile.picPathString)) {
				removeIndex = i;
				break;
			}
		}
		mUploadFileList.remove(removeIndex);
	}

	private synchronized void uploadFile(final UploadFile uploadFile) {

		DebugLog.logI("uploadFile11111111111111111111111111111111111");

		String picPathString = uploadFile.picPathString
				.replace("file:///", "/");
		StringBuilder studentIdStringBuilder = new StringBuilder();
		if (uploadFile.studentIdList.size() > 0) {
			for (int i = 0; i < uploadFile.studentIdList.size(); i++) {
				studentIdStringBuilder.append(uploadFile.studentIdList.get(i))
						.append(",");
			}
			studentIdStringBuilder.delete(studentIdStringBuilder.length() - 1,
					studentIdStringBuilder.length());
		}

		String fname = null;
		String ftime = null;
		if (!TextUtils.isEmpty(picPathString)) {
			File file= new File(picPathString);
			ftime = (file.lastModified()/1000) + "";
			// fbody = PictureUtil.getPicString(picPathString, 512);
			// fext = picPathString.substring(picPathString.lastIndexOf(".") +
			// 1);
			fname = picPathString.substring(picPathString.lastIndexOf("/") + 1);
			// fsize = fbody.length() + "";
		}

		uploadFile.requestHandle = NetworkClientSingle.getNetworkClient()
				.PostRequest(
						new UploadFileRequest(mContext, picPathString, fname,
								studentIdStringBuilder.toString(),
								mApplication.mClassInfo.uid, uploadFile.intro,
								uploadFile.photoTag,
								mApplication.mTeacher.teacherid,ftime),
						new UploadFileResponse() {
							@Override
							public void onResponse(
									ResponseHandlerInterface responseHandlerInterface) {
								if ("1".equals(code)) {

									// 上传成功，更新上传列表
									UploadFileDB uploadFileDB = UploadFileDB
											.getUploadFileDB(mContext);
									uploadFileDB.remove(uploadFile);
									uploadFileDB.close();

									mUploadFileList.remove(uploadFile);

									// 刷新列表
									Intent intent = new Intent();
									intent.setAction(UploadListFragment.ACTION_UPDATE_UPLOAD_LIST);
									mContext.sendBroadcast(intent);

									// TODO:测试
									// HandlerToastUI.getHandlerToastUI(mContext,
									// "code=" + code + " " +
									// uploadFile.picFileString + " 上传成功");

									if (0 == mUploadFileList.size()) {
//										HandlerToastUI.getHandlerToastUI(
//												mContext, "恭喜你，所有照片和视频上传成功",
//												android.R.color.white);
										HandlerToastUI.getHandlerToastUI(
												mContext, mContext.getString(R.string.all_uploaded_successfully));
									}

									uploadFirstFile();
									
								} else if ("-44".equals(code)) {
									HandlerToastUI.getHandlerToastUI(mContext,
											"ffmpeg没有载入");
								} else {
									HandlerToastUI.getHandlerToastUI(mContext,
											"code=" + code + " "
													+ uploadFile.picFileString
													+ " 上传失败");
								}
							}
						}, new IStateListener() {

							@Override
							public void onStart(
									AsyncHttpRequest asyncHttpRequest) {

							}

							@Override
							public void onRetry(int retryNo) {

							}

							@Override
							public void onProgress(int bytesWritten,
									int totalSize) {
								uploadFile.progress = (int) (((double) bytesWritten / (double) totalSize) * 100);
								DebugLog.logI(uploadFile.picFileString + " "
										+ uploadFile.progress + "%");
//								try {
//									TimeUnit.MILLISECONDS.sleep(500);
//								} catch (InterruptedException e) {
//									e.printStackTrace();
//								}
								if (null != mFragment) {
									if (mFragment instanceof UploadListFragment) {
										HandlerPostUI
												.getHandlerPostUI(new Runnable() {

													@Override
													public void run() {
														UploadListFragment fragment = (UploadListFragment) mFragment;
														View view = fragment.mUploadFileAdapter
																.getFirstView();
														if (null != view) {
															TextView progressTextView = (TextView) view
																	.findViewById(R.id.progressTextView);
															progressTextView
																	.setText(uploadFile.progress
																			+ "%");
														}
													}
												});
									}
								}
							}

							@Override
							public void onFinish(
									AsyncHttpRequest asyncHttpRequest) {
								
//								HandlerToastUI.getHandlerToastUI(mContext, "onFinish");
								
//								uploadFile.future = null;
								uploadFile.requestHandle = null;
								uploadFile.progress = 0;
							}

							@Override
							public void onCancel() {

							}
						}, new IErrorListener() {

							@Override
							public void onFailure(int statusCode,
									Header[] headers, byte[] responseBody,
									Throwable error) {
								// 错误处理，删除上传的请求从新开始发送，从第一个开始
								// if (mUploadFileList.size() > 0) {
								// uploadFile(mUploadFileList.get(0));
								// }
							}
						});
	}

}
